//
//  WBMainViewController.swift
//  传智微博
//
//  Created by wong on 16/12/8.
//  Copyright © 2016年 Canis. All rights reserved.
//
//WBMainViewController: 用反射添加子控制器，添加中间的撰写按钮

import UIKit
import SVProgressHUD
//主控制器

class WBMainViewController: UITabBarController {
    
    //定时器
    var timer:Timer?
    
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupChildControllers()
        setupComposeButton()
        setupTimer()
        
        //设置代理
        delegate = self
        
        //注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
    }
    
    deinit{
        //销毁时钟
        timer?.invalidate()
        
        //注销通知
        NotificationCenter.default.removeObserver(self)
    }
    
    //portrait: 竖屏
    //landscape: 横屏
    
    //使用代码控制设备的方向，好处：可以在需要横屏的时候单独处理
    //设置成支持的方向之后，当前的控制器及子控制器都会遵守这个方向!
    //视频横屏 通常是通过 modal 展现的
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        return .portrait
    }
    
    //MARK: -监听方法
    
    
    func userLogin(n:Notification){
        print("用户登录通知 \(n)")
        
        var when = DispatchTime.now()
        //判断 n.object 是否有值 -> token 过期 ，提示用户重新登录
        if n.object != nil{
            //设置指示器渐变样式
            SVProgressHUD.setDefaultMaskType(.gradient)
            SVProgressHUD.showInfo(withStatus: "用户登录已经超时，需要重新登录")
            
            //修改延迟时间
            when = DispatchTime.now() + 2
        }
        DispatchQueue.main.asyncAfter(deadline: when) {
            SVProgressHUD.setDefaultMaskType(.clear)
            //展现用户登录控制器 - 通常会和 UINavigationController 连用，方便返回
            let nav = UINavigationController(rootViewController:WBOAuthViewController())
            
            self.present(nav,animated: true,completion: nil)
            
        }
    }
    
    
    //撰写微博 
    //FIXME: 没有实现
    func composeStatus(){
        print("撰写微博")
        
        //测试方向旋转
        let vc = UIViewController()
        vc.view.backgroundColor = UIColor.cz_random()
        let nav = UINavigationController(rootViewController: vc)
        present(vc, animated: true, completion: nil)
        
        
    }
    
    //MARK: -私有控件
    //撰写按钮
     lazy var composeButton:UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
}

// MARK: - UITabBarControllerDelegate
extension WBMainViewController: UITabBarControllerDelegate{
    /// 将要选择 TabBarItem
    ///
    /// - Parameters:
    ///   - tabBarController: tabBarController
    ///   - viewController:   目标控制器
    /// - Returns: 是否切换到目标控制器
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        print("将要切换到 \(viewController)")
        //1>获取控制器在数组中的索引
        let idx = (childViewControllers as NSArray).index(of: viewController)
        
        //2>判断当前索引是首页，同时 idx 也是首页，重复点击首页按钮
        if selectedIndex == 0 && idx == selectedIndex{
            print("点击首页")
            //3>让表格滚动到顶部
            //a) 获取到控制器
            let nav = childViewControllers[0] as! UINavigationController
            let vc  = nav.childViewControllers[0] as! WBHomeViewController
            //b) 滚动到顶部
            vc.tableView?.setContentOffset(CGPoint(x: 0, y: -64), animated: true)
            
            //4>刷新数据 - 增加延迟，是保证表格先滚动到顶部再刷新
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1, execute: {
                vc.loadData()
            })
            
        }
        
        //判断目标控制器是否是 UIViewController
        
        return !viewController.isMember(of: UIViewController.self)

    }
}

// MARK: - 时钟相关方法
extension WBMainViewController{
     func setupTimer(){
        //时间间隔建议长一些
        timer = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    
    /// 时钟触发方法
    func updateTimer(){
        if !WBNetworkManager.shared.userLogon{
            return
        }
        
        WBNetworkManager.shared.unreadCount { (count) in
            print("检测到 \(count) 条新微博")
            //设置首页 tabBarItem 的 badgeNumber
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
            
            //设置 App badgeNumber, 从 IOS 8.0之后，要用户授权之后才能显示
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }
}

//extension 类似于OC中的分类，在 swift 中还可以用来切分代码块
//可以吧相近功能的函数，放在一个 extension 中
//便于代码维护
//注意：和OC的分类一样，extension中不能定义属性
extension WBMainViewController{
    
    //设置撰写按钮
    func setupComposeButton(){
        tabBar.addSubview(composeButton)
        
        //计算按钮的宽度
        let count = CGFloat(childViewControllers.count)
        
        //将向内缩进的宽度减少，能够让按钮宽度变大，盖住容错点，防止穿帮！
        let w = tabBar.bounds.width / count 
        
        // CGRectInset 正数向内缩进，负数向外扩展
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        
        //按钮监听方法
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
        
        
    }
    ///设置所有子控制器
    func setupChildControllers(){
        
        //0.获取沙盒的json路径
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        
        //加载data
        var data = NSData(contentsOfFile:jsonPath)
        
        //判断data是否有内容,如果没有，说明本地沙盒没有文件
        if data == nil{
            //从 bundle 加载 data
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            data = NSData(contentsOfFile: path!)
        }
        
        //data 一定会有一个内容，反序列化
        
        
        
        //反序列化转换成数组
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String: AnyObject]]
        
        else{
            return
        }
        
        //遍历数组，循环创建控制器数组
        var arrayM = [UIViewController]()
        for dict in array! {
            arrayM.append(controller(dict: dict as [String : AnyObject]))
        }
        //设置tabbar 的子控制器
        viewControllers = arrayM
    }
    
    /// 使用字典创建一个子控制器
    ///
    /// - parameter dict: 信息字典[clsName, title, imageName,"visitorInfo"]
    ///
    /// - returns:子控制器
    
    private func controller(dict: [String: AnyObject]) -> UIViewController {
        //1. 取得字典内容
        guard let clsName = dict["clsName"] as? String,
                 let title = dict["title"] as? String,
                 let imageName = dict["imageName"] as? String,
                 let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type,
                 let visitorDict = dict["visitorInfo"] as? [String:String]
            else {
                return UIViewController()
            }
        //2. 创建视图控制器
        let vc = cls.init()
        vc.title = title
        
        //设置控制器的访客信息字典
        vc.visitorInfoDictionary = visitorDict
        
        //3. 设置图像
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)

        //4. 设置 tabbar 的标题字体 (大小)
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .highlighted)
        //系统默认是12号字，修改字体大小，要设置 Normal 的字体大小
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 12)], for: UIControlState(rawValue: 0))
        
        //实例化导航控制器的时候，会调用push方法将rootVC 压栈
        let nav = WBNavigationController(rootViewController: vc)
        
        return nav
        
    }
}
